package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import top.littlejiang.onlinexam.entity.OlexamMenuRole;
import top.littlejiang.onlinexam.mapper.OlexamMenuRoleMapper;
import top.littlejiang.onlinexam.service.OlexamMenuRoleService;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * OlexamMenuRole 服务实现类
 * </p>
 *
 * @author chen
 * @since 2020-12-26
 */
@Service
public class OlexamMenuRoleServiceImpl extends BaseServiceImpl<OlexamMenuRoleMapper, OlexamMenuRole> implements OlexamMenuRoleService {

    /**
     * 根据角色查询菜单id
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> getMenusByRole(int roleId) {
        List<Integer> checked = this.baseMapper.getMenusByRole(roleId);
        return checked;
    }

    /**
     * 更新角色菜单
     *
     * @param newMenus
     * @param roleId
     */
    @Override
    public void insertOrDelete(List<Integer> newMenus, Integer roleId) {
        List<Integer> oldMenus = this.getMenusByRole(roleId);
        List<Integer> same = newMenus.stream().filter(p -> oldMenus.contains(p)).collect(Collectors.toList());
        newMenus.removeAll(same);
        oldMenus.removeAll(same);
        List<OlexamMenuRole> toAdd = new ArrayList<>();

        if (oldMenus.size() > 0){
            QueryWrapper<OlexamMenuRole> wrapper = new QueryWrapper<>();
            wrapper.in("fk_menu_id", oldMenus);
            wrapper.eq("fk_role_id", roleId);
            this.getBaseMapper().delete(wrapper);
        }
        if (newMenus.size() > 0){
            newMenus.forEach(a -> {
                toAdd.add(new OlexamMenuRole().setFkMenuId(a)
                        .setFkRoleId(roleId)
                        .setIsDel(0));
            });
            this.saveBatch(toAdd);
        }
    }
}
